﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;
using System.Xml.XPath;
using SaaS;

public partial class ObjectEdit : System.Web.UI.Page
{
    //Note: For now, primary key value cannot be edited. It takes a lot of work to add all this data
    //to the KEYS table and all the data added needs to be distinct... May get to this issue later.

    //Known issue: if the last column is removed then a new column added, the Column ID of the new column
    //will be the same as the one that was just removed
    protected void Page_Load(object sender, EventArgs e)
    {
        if (ddlType.Items.Count == 0)
        {
            string[] typeString = { "int", "double", "bool", "string" };
            for (int i = 0; i < typeString.Length; i++)
            {
                ddlType.Items.Add(typeString[i]);
            }
        }

        if (Session.Count != 0 & ddbObjName.Items.Count==0)
        {
            string strConnection = "workstation id=MiniSaaS.mssql.somee.com;packet size=4096;user id=SaaS_cse564;pwd=123abccse;data source=MiniSaaS.mssql.somee.com;persist security info=False;initial catalog=MiniSaaS";
            System.Data.SqlClient.SqlConnection Connection = new System.Data.SqlClient.SqlConnection(strConnection);
            string loginID = Session["LoginID"].ToString();
            //String strSQL = "Select Table_Name, Table_Version From META WHERE Login_ID = '" + loginID + "';";
            String strSQL = "Select DISTINCT Table_ID From META WHERE Login_ID = " + loginID + ";";
            System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(strSQL, Connection);
            System.Data.SqlClient.SqlDataReader Dr;
            Connection.Open();
            Dr = command.ExecuteReader();
            System.Collections.Generic.List<int> tableIDs = new System.Collections.Generic.List<int>();
            while (Dr.Read())
                tableIDs.Add((int)Dr["Table_ID"]);
            Dr.Close();
            ddbObjName.Items.Insert(0, new ListItem("", ""));
            for (int i = 0; i < tableIDs.Count; i++)
            {
                strSQL = "SELECT Table_Name FROM META WHERE Table_ID = " + tableIDs[i].ToString() + " AND Table_Version = (SELECT MAX(Table_Version) FROM META WHERE Table_ID = " + tableIDs[i].ToString() + ")";
                command = new System.Data.SqlClient.SqlCommand(strSQL, Connection);
                Dr = command.ExecuteReader();
                Dr.Read();
                ddbObjName.Items.Add(Dr["Table_Name"].ToString());
                Session["TableID" + (i+1).ToString()] = tableIDs[i].ToString();
                Dr.Close();
            }
            //while (Dr.Read())
            //{
            //    ddbObjName.Items.Add(Dr["Table_Name"].ToString()+"||Version:"+Dr["Table_Version"]);
            //}
            Connection.Close();
            Dr.Close();
        }
    }
    protected void ddbObjName_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddbObjName.SelectedIndex > 0)
        {
            string selectVal = ddbObjName.SelectedValue;
            string TableName = selectVal;
        
            btnViewDat.Enabled = true;

            string strConnection = "workstation id=MiniSaaS.mssql.somee.com;packet size=4096;user id=SaaS_cse564;pwd=123abccse;data source=MiniSaaS.mssql.somee.com;persist security info=False;initial catalog=MiniSaaS";
            System.Data.SqlClient.SqlConnection Connection = new System.Data.SqlClient.SqlConnection(strConnection);
            string loginID = Session["LoginID"].ToString();
            string tableID = Session["TableID" + ddbObjName.SelectedIndex.ToString()].ToString();
            int tableVer;
            String strSQL = "SELECT MAX(Table_Version) FROM META WHERE Table_ID = " + tableID;
            //String strSQL = "Select Table_Columns From META WHERE Login_ID = '" + loginID + "'and Table_Name = '" + TableName + "' and Table_Version = '" + TableVersion + "';";
            System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(strSQL, Connection);
            System.Data.SqlClient.SqlDataReader Dr;
            Connection.Open();
            Dr = command.ExecuteReader();
            if (!Dr.HasRows)
            {
                //error- could not find table ID
                return;
            }
            Dr.Read();
            tableVer = (int)Dr[0];
            Dr.Close();
            //txtVersion.Text = tableVer.ToString();
            strSQL = "Select * From META WHERE Table_ID = "+tableID+" and Table_Version = " + tableVer.ToString() + ";";
            command = new System.Data.SqlClient.SqlCommand(strSQL, Connection);
            Dr = command.ExecuteReader();
            Dr.Read();
            string TableColumns = Dr["Table_Columns"].ToString();
            Session["xml"] = TableColumns;
            lblTableID.Text = Dr["Table_ID"].ToString();
            lblTableVer.Text = tableVer.ToString();

            Session["TableID"] = lblTableID.Text.Trim();
            Session["TableVer"] = tableVer.ToString();

            lblCount.Text = Dr["Table_Columns_Count"].ToString();
            txtDsp.Text = Dr["Table_Description"].ToString();
            Dr.Close();

            Connection.Close();

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(TableColumns);
            doc.Save(Server.MapPath("~/App_Data/TempObject.xml"));
            XmlDataSource1.DataFile = "~/App_Data/TempObject.xml";
            XmlDataSource1.XPath = "//col/*/text()";

            DataSet dataSet = new DataSet();
            dataSet.ReadXml(Server.MapPath("~/App_Data/TempObject.xml"));
            this.GridView1.DataMember = "col";
            this.GridView1.DataSource = dataSet;
            this.GridView1.DataBind();

            txtNameInput.Text = "";
            txtName.Text = "";
            ddlType.SelectedIndex = 0;
            //txtType.Text = "";
            //txtVersion.Text = "";
            txtDefault.Text = "";
            rdoNullTrue.Checked = true;
            rdoPriKeyFalse.Checked = true;
        }
        else
            btnViewDat.Enabled = false;

    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {

    }

    protected void btnShow_Click(object sender, EventArgs e)
    {
        string showName = txtNameInput.Text.Trim();
        XmlDocument doc = new XmlDocument();
        //doc.Load("~/App_Data/TempObject.xml");
        doc.LoadXml(Session["xml"].ToString());
        XmlNodeList xnl = doc.SelectNodes("//col/name");
        foreach (XmlNode xn in xnl)
        {
            if (xn.InnerText.ToString() == showName)
            {
                txtName.Text = xn.InnerText.ToString();
                //txtType.Text =  
                string type = xn.ParentNode.SelectSingleNode("type").InnerText.ToString();
                if (type.Equals("int", StringComparison.CurrentCultureIgnoreCase))
                    ddlType.SelectedIndex = 0;
                else if (type.Equals("double", StringComparison.CurrentCultureIgnoreCase))
                    ddlType.SelectedIndex = 1;
                else if (type.Equals("bool", StringComparison.CurrentCultureIgnoreCase))
                    ddlType.SelectedIndex = 2;
                else
                    ddlType.SelectedIndex = 3;
                if (!xn.ParentNode.SelectSingleNode("allownull").InnerText.ToString().Equals("True",StringComparison.CurrentCultureIgnoreCase))
                    rdoNullFalse.Checked = true;
                else
                    rdoNullTrue.Checked = true;
                if (xn.ParentNode.SelectSingleNode("PriKey") == null || !xn.ParentNode.SelectSingleNode("PriKey").InnerText.ToString().Equals("True", StringComparison.CurrentCultureIgnoreCase))
                    rdoPriKeyFalse.Checked = true;
                else
                    rdoPriKeyTrue.Checked = true;
                if (xn.ParentNode.SelectSingleNode("default")!=null)
                    txtDefault.Text = xn.ParentNode.SelectSingleNode("default").InnerText.ToString();
                //txtVersion.Text = Session["TableVer"].ToString();
                break;
            }
            
        }

    }
    protected void btnEdit_Click(object sender, EventArgs e)
    {
        //txtVersion.ReadOnly = false;
        txtName.ReadOnly = false;
        //txtType.ReadOnly = false;
        ddlType.Enabled = true;
        txtDefault.ReadOnly = false;
        rdoNullFalse.Enabled = true;
        rdoNullTrue.Enabled = true;
        //rdoPriKeyFalse.Enabled = true;
        //rdoPriKeyTrue.Enabled = true;
        txtNameInput.ReadOnly = true;

        btnSubmit.Enabled = true;
        btnCancel.Enabled = true;
    }

    //update
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string showName = txtNameInput.Text.Trim();
        XmlDocument xd = new XmlDocument();
        xd.LoadXml(Session["xml"].ToString());
        XmlNodeList xnl = xd.SelectNodes("//col/name");
        foreach (XmlNode xn in xnl)
        {
            if (xn.InnerText.ToString() == showName)
            {
                //name
                xn.InnerText = txtName.Text.Trim();
                //type
                XmlNode xn2= xn.NextSibling;   
                //xn2.InnerText = txtType.Text.Trim();
                xn2.InnerText = ddlType.Text;
                //allow null
                XmlNode xn3 = xn2.NextSibling;
                xn3.InnerText = rdoNullTrue.Checked ? "True" : "False";
                //default value
                XmlNode xn4 = xn3.NextSibling;
                xn4.InnerText = txtDefault.Text.Trim();
                //skip column ID if prsent
                XmlNode xn5 = xn4.NextSibling;
                while (xn5 != null && !xn5.Name.Equals("priKey"))
                    xn5 = xn5.NextSibling;
                if (xn5 != null)
                {
                    //primary key (if present)
                    xn5.InnerText = rdoPriKeyTrue.Checked ? "True" : "False";
                }
                
                //xn.ParentNode.RemoveAll();
                break;

            }
        }

        System.IO.StringWriter sw = new System.IO.StringWriter();
        XmlTextWriter xw = new XmlTextWriter(sw);
        xd.WriteTo(xw);
        string xmlStr = sw.ToString();
        
        string strLogId = Session["LoginID"].ToString();

        //update version only if data references the old version
        bool createNewVersion = false;
        int nextVersion = -1;
        
        string strTableName = ddbObjName.SelectedValue;
        string strTableId = lblTableID.Text.Trim();
        string strCount = lblCount.Text.Trim();
        string strDsp = txtDsp.Text.Trim();

        string query = "SELECT * FROM DATA WHERE Table_ID = '" + strTableId + "' AND Table_Version = " + Session["TableVer"].ToString();

        System.Data.SqlClient.SqlConnection con;
        con = new System.Data.SqlClient.SqlConnection();
        con.ConnectionString = "workstation id=MiniSaaS.mssql.somee.com;packet size=4096;user id=SaaS_cse564;pwd=123abccse;data source=MiniSaaS.mssql.somee.com;persist security info=False;initial catalog=MiniSaaS";
        con.Open();
        System.Data.SqlClient.SqlCommand cmd;

        cmd = new System.Data.SqlClient.SqlCommand(query, con);
        System.Data.SqlClient.SqlDataReader Dr = cmd.ExecuteReader();
        if (Dr.HasRows)
        {
            //There is data referencing the latest version of the table - Create new
            Dr.Close();
            createNewVersion = true;
            query = "SELECT MAX(Table_Version)+1 FROM META WHERE Table_ID = " + strTableId;
            cmd = new System.Data.SqlClient.SqlCommand(query, con);
            Dr = cmd.ExecuteReader();
            Dr.Read();
            nextVersion = (int)Dr[0];
        }
        Dr.Close();

        String strCommand;
        if (createNewVersion)
        {
            //create new table entry
            strCommand = "INSERT INTO META (Table_ID, Table_Version, Login_ID, Table_Name, Table_Columns_Count, Table_Columns, Table_Description) VALUES(";
            strCommand += strTableId + "," + nextVersion.ToString() + "," + strLogId + ", '" + strTableName + "'," + strCount + ",'" + xmlStr + "','" + strDsp + "');";
            lblTableVer.Text = nextVersion.ToString();
        }
        else
        {
            //update
            strCommand = "UPDATE META " +
                "SET Table_Name = '" + strTableName + "', " +
                "Table_Columns_Count = " + strCount + ", " +
                "Table_Columns = '" + xmlStr + "', " +
                "Table_Description = '" + strDsp + "' " +
                "WHERE Table_ID = " + strTableId + " AND " +
                "Table_Version = " + Session["TableVer"].ToString();
        }
            
        cmd = new System.Data.SqlClient.SqlCommand(strCommand, con);
        int rows = cmd.ExecuteNonQuery();
        con.Close();

        txtNameInput.Text = "";
        txtName.Text = "";
        ddlType.SelectedIndex = 0;
        //txtType.Text = "";
        //txtVersion.Text = "";
        rdoNullTrue.Checked = true;
        rdoPriKeyFalse.Checked = true;
        lblCount.Text = "";

        txtName.ReadOnly = true;
        //txtType.ReadOnly = true;
        ddlType.Enabled = false;
        txtDefault.ReadOnly = true;
        rdoNullFalse.Enabled = false;
        rdoNullTrue.Enabled = false;
        rdoPriKeyFalse.Enabled = false;
        rdoPriKeyTrue.Enabled = false;
        //txtVersion.ReadOnly = true;
        txtNameInput.ReadOnly = false;

        btnSubmit.Enabled = false;
        btnCancel.Enabled = false;

        //string toAdd = strTableName+"||Version:"+strTableVersion;
        //ddbObjName.Items.Add(toAdd);

        //ddbObjName.SelectedIndex = 0;

        GridView1.DataSource = "";
        GridView1.DataBind();

        ddbObjName_SelectedIndexChanged(null, null);
    }
    protected void btnDel_Click(object sender, EventArgs e)
    {
        int strTableVersion = int.Parse(Session["TableVer"].ToString());
        int strTableId = int.Parse(Session["TableID"].ToString());

        //Need to delete all data associated with table as well
        string strCommand = "DELETE FROM KEYS WHERE Data_ID IN (SELECT Data_ID FROM " +
            "DATA WHERE Table_ID = " + strTableId + "); ";
        strCommand += "DELETE FROM DATA WHERE Table_ID = " + strTableId + "; ";
        strCommand += "DELETE META WHERE Table_ID = " + strTableId + ";";

        System.Data.SqlClient.SqlConnection con;
        con = new System.Data.SqlClient.SqlConnection();
        con.ConnectionString = "workstation id=MiniSaaS.mssql.somee.com;packet size=4096;user id=SaaS_cse564;pwd=123abccse;data source=MiniSaaS.mssql.somee.com;persist security info=False;initial catalog=MiniSaaS";
        con.Open();
        System.Data.SqlClient.SqlCommand cmd;
        cmd = new System.Data.SqlClient.SqlCommand(strCommand, con);
        int rows = cmd.ExecuteNonQuery();
        con.Close();

        string toDel = ddbObjName.SelectedValue.ToString();

        ddbObjName.Items.Remove(toDel);
        ddbObjName.SelectedIndex = 0;

        GridView1.DataSource = "";
        GridView1.DataBind();

        txtNameInput.Text = "";
        txtName.Text = "";
        ddlType.SelectedIndex = 0;
        //txtType.Text = "";
        //txtVersion.Text = "";
        rdoNullTrue.Checked = true;
        rdoPriKeyFalse.Checked = true;
        lblCount.Text = ""; 
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        txtName.ReadOnly = true;
        //txtType.ReadOnly = true;
        ddlType.Enabled = false;
        txtDefault.ReadOnly = true;
        rdoNullFalse.Enabled = false;
        rdoNullTrue.Enabled = false;
        rdoPriKeyFalse.Enabled = false;
        rdoPriKeyTrue.Enabled = false;
        txtNameInput.ReadOnly = false;
        //txtVersion.ReadOnly = true;
        
        //txtVersion.Text = "";
        txtNameInput.Text = "";
        txtName.Text = "";
        ddlType.SelectedIndex = 0;
        //txtType.Text = "";
        //txtVersion.Text = "";
        rdoNullTrue.Checked = true;
        rdoPriKeyFalse.Checked = true;
        lblCount.Text = "";
        txtDefault.Text = "";

        btnSubmit.Enabled = false;
        btnCancel.Enabled = false;
        btnInsert.Enabled = false;

        lblNote.Visible = false;
    }
    protected void btnViewDat_Click(object sender, EventArgs e)
    {
        
    }
    protected void btnNew_Click(object sender, EventArgs e)
    {
        lblNote.Visible = true;
        btnInsert.Enabled = true;
        btnCancel.Enabled = true;
        btnSubmit.Enabled = false;

        txtName.Text = "";
        ddlType.SelectedIndex = 0;
        //txtType.Text = "";
        rdoNullTrue.Checked = true;
        rdoPriKeyFalse.Checked = true;
        txtDefault.Text = "";
        //txtVersion.Text = "";
        txtNameInput.Text = "";

        txtName.ReadOnly = false;
        ddlType.Enabled = true;
        //txtType.ReadOnly = false;
        txtDefault.ReadOnly = false;
        rdoNullFalse.Enabled = true;
        rdoNullTrue.Enabled = true;
        //rdoPriKeyFalse.Enabled = true;
        //rdoPriKeyTrue.Enabled = true;
        txtNameInput.ReadOnly = true;
        //txtVersion.ReadOnly = false;
    }
    protected void btnInsert_Click(object sender, EventArgs e)
    {
        string strLogId = Session["LoginID"].ToString();
        string strTableName = ddbObjName.SelectedValue;
        string strTableId = lblTableID.Text.Trim();
        string strCount = (int.Parse(lblCount.Text.Trim()) + 1).ToString();
        string strDsp = txtDsp.Text.Trim();
        
        
        string showName = txtNameInput.Text.Trim();
        XmlDocument xd = new XmlDocument();
        xd.LoadXml(Session["xml"].ToString());

        XmlNodeList xnl = xd.SelectNodes("//col/columnID");
        int maxID = 0;
        foreach (XmlNode xn in xnl)
        {
            int id = int.Parse(xn.InnerText.ToString());
            if (id > maxID)
                maxID = id; 
        } 

        XmlNode xnd = xd.SelectSingleNode("columns");
        XmlElement xe_u = xd.CreateElement("col");
        XmlElement xe_a1 = xd.CreateElement("name");
        xe_a1.InnerText = txtName.Text.Trim();
        xe_u.AppendChild(xe_a1);
        XmlElement xe_a2 = xd.CreateElement("type");
        //xe_a2.InnerText = txtType.Text.Trim() ;
        xe_a2.InnerText = ddlType.Text;
        xe_u.AppendChild(xe_a2);
        XmlElement xe_a3 = xd.CreateElement("allownull");
        xe_a3.InnerText = rdoNullTrue.Checked ? "True" : "False";
        xe_u.AppendChild(xe_a3);
        XmlElement xe_a4 = xd.CreateElement("default");
        xe_a4.InnerText = txtDefault.Text.Trim();
        xe_u.AppendChild(xe_a4);
        XmlElement xe_a5 = xd.CreateElement("columnID");
        xe_a5.InnerText = (maxID + 1).ToString();
        xe_u.AppendChild(xe_a5);
        XmlElement xe_a6 = xd.CreateElement("priKey");
        xe_a6.InnerText = rdoPriKeyTrue.Checked ? "True" : "False";
        xe_u.AppendChild(xe_a6);
        
        xnd.AppendChild(xe_u);
        
        System.IO.StringWriter sw = new System.IO.StringWriter();
        XmlTextWriter xw = new XmlTextWriter(sw);
        xd.WriteTo(xw);
        string xmlStr = sw.ToString();

        MiniSaaSDB db = new MiniSaaSDB();
        db.open();

        string query = "SELECT * FROM DATA WHERE Table_ID = '" + strTableId + "' AND Table_Version = " + Session["TableVer"].ToString();
        System.Data.SqlClient.SqlDataReader Dr = db.executeQuery(query);

        string strCommand;
        if (Dr != null && Dr.HasRows)
        {
            //There is data referencing the latest version of the table - Create new
            int nextVersion = -1;
            query = "SELECT MAX(Table_Version)+1 FROM META WHERE Table_ID = " + strTableId;
            Dr = db.executeQuery(query);
            Dr.Read();
            nextVersion = (int)Dr[0];

            //create new table entry
            strCommand = "INSERT INTO META (Table_ID, Table_Version, Login_ID, Table_Name, Table_Columns_Count, Table_Columns, Table_Description) VALUES(";
            strCommand += strTableId + "," + nextVersion.ToString() + "," + strLogId + ", '" + strTableName + "'," + strCount + ",'" + xmlStr + "','" + strDsp + "');";
            lblTableVer.Text = nextVersion.ToString();
        }
        else
        {
            //update
            strCommand = "UPDATE META " +
                "SET Table_Name = '" + strTableName + "', " +
                "Table_Columns_Count = " + strCount + ", " +
                "Table_Columns = '" + xmlStr + "', " +
                "Table_Description = '" + strDsp + "' " +
                "WHERE Table_ID = " + strTableId + " AND " +
                "Table_Version = " + Session["TableVer"].ToString();
        }

        int rows = db.executeNonQuery(strCommand);
        db.close();

        txtNameInput.Text = "";
        txtName.Text = "";
        ddlType.SelectedIndex = 0;
        //txtType.Text = "";
        //txtVersion.Text = "";
        rdoNullTrue.Checked = true;
        rdoPriKeyFalse.Checked = true;
        lblCount.Text = "";

        txtName.ReadOnly = true;
        ddlType.Enabled = false;
        //txtType.ReadOnly = true;
        txtDefault.ReadOnly = true;
        rdoNullFalse.Enabled = false;
        rdoNullTrue.Enabled = false;
        rdoPriKeyFalse.Enabled = false;
        rdoPriKeyTrue.Enabled = false;
        //txtVersion.ReadOnly = true;
        txtNameInput.ReadOnly = false;

        btnInsert.Enabled = false;

        lblNote.Visible = false;

        //string toAdd = strTableName + "||Version:" + strTableVersion;
        //ddbObjName.Items.Add(toAdd);

        //ddbObjName.SelectedIndex = 0;

        GridView1.DataSource = "";
        GridView1.DataBind();

        ddbObjName_SelectedIndexChanged(null, null);
    }

    protected void btnDelCol_Click(object sender, EventArgs e)
    {
        string showName = txtNameInput.Text.Trim();
        XmlDocument xd = new XmlDocument();
        xd.LoadXml(Session["xml"].ToString());
        string xp = "//col[./name='" + showName + "']";
        XmlNode xn = xd.SelectSingleNode(xp);
        xn.RemoveAll();
        xn.ParentNode.RemoveChild(xn);

        System.IO.StringWriter sw = new System.IO.StringWriter();
        XmlTextWriter xw = new XmlTextWriter(sw);
        xd.WriteTo(xw);
        string xmlStr = sw.ToString();

        string strLogId = Session["LoginID"].ToString();
        //string strTableVersion = txtVersion.Text.Trim();
        string strTableName = ddbObjName.SelectedValue;
        string strTableId = lblTableID.Text.Trim();
        string strCount = (int.Parse(lblCount.Text.Trim())-1).ToString();
        string strDsp = txtDsp.Text.Trim();


        System.Data.SqlClient.SqlConnection con;
        con = new System.Data.SqlClient.SqlConnection();
        con.ConnectionString = "workstation id=MiniSaaS.mssql.somee.com;packet size=4096;user id=SaaS_cse564;pwd=123abccse;data source=MiniSaaS.mssql.somee.com;persist security info=False;initial catalog=MiniSaaS";
        con.Open();
        System.Data.SqlClient.SqlCommand cmd;

        string query = "SELECT * FROM DATA WHERE Table_ID = '" + strTableId + "' AND Table_Version = " + Session["TableVer"].ToString();
        cmd = new System.Data.SqlClient.SqlCommand(query, con);
        System.Data.SqlClient.SqlDataReader Dr = cmd.ExecuteReader();

        string strCommand;
        if (Dr != null && Dr.HasRows)
        {
            //There is data referencing the latest version of the table - Create new
            int nextVersion = -1;
            Dr.Close();
            query = "SELECT MAX(Table_Version)+1 FROM META WHERE Table_ID = " + strTableId;
            cmd = new System.Data.SqlClient.SqlCommand(query, con);
            Dr = cmd.ExecuteReader();
            Dr.Read();
            nextVersion = (int)Dr[0];

            //create new table entry
            strCommand = "INSERT INTO META (Table_ID, Table_Version, Login_ID, Table_Name, Table_Columns_Count, Table_Columns, Table_Description) VALUES(";
            strCommand += strTableId + "," + nextVersion.ToString() + "," + strLogId + ", '" + strTableName + "'," + strCount + ",'" + xmlStr + "','" + strDsp + "');";
            lblTableVer.Text = nextVersion.ToString();
        }
        else
        {
            //update
            Dr.Close();
            strCommand = "UPDATE META " +
                "SET Table_Name = '" + strTableName + "', " +
                "Table_Columns_Count = " + strCount + ", " +
                "Table_Columns = '" + xmlStr + "', " +
                "Table_Description = '" + strDsp + "' " +
                "WHERE Table_ID = " + strTableId + " AND " +
                "Table_Version = " + Session["TableVer"].ToString();
        }

        cmd = new System.Data.SqlClient.SqlCommand(strCommand, con);
        int rows = cmd.ExecuteNonQuery();
        con.Close();

        //string toAdd = strTableName + "||Version:" + strTableVersion;
        //ddbObjName.Items.Add(toAdd);

        //ddbObjName.SelectedIndex = 0;

        GridView1.DataSource = "";
        GridView1.DataBind();

        ddbObjName_SelectedIndexChanged(null, null);

        //txtVersion.Text = "";
        lblCount.Text = "";

    }

    protected void btnEditData_Click(object sender, EventArgs e)
    {
        Response.Redirect("DataEdit.aspx");
    }
}
